package dumu

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fsdvgw/config"
	"fsdvgw/repo"
	"github.com/gin-gonic/gin"
	"github.com/go-resty/resty/v2"
	"io"
	"log"
	"net/http"
)

var serverBase = config.GetConf().ServerAddress
var defaultPassword = md5Str("123456")

// HandleHeartbeatCallback 心跳回调函数
func HandleHeartbeatCallback(c *gin.Context) {
	req := new(heartbeatRequest)
	err := c.ShouldBindJSON(req)
	if err != nil {
		c.JSON(http.StatusBadRequest, failedResponse)
		return
	}

	dev, exist := repo.GetDeviceByFactoryIdentity(req.DeviceId)
	//自发现？库里没有，就创建设备；库里已有，就对比IP是否一样
	if !exist {
		err = repo.CreateDynamicDevice(&repo.DynamicDeviceParam{
			Model:    req.DeviceCode,
			DeviceId: req.DeviceId,
			IP:       req.IP,
			Context:  defaultPassword, //度目默认密码
		})
		if err != nil {
			c.JSON(http.StatusInternalServerError, failedResponse)
			return
		}
		err = registerRecognizeCallbackToDevice(req.IP)
		if err != nil {
			log.Println(err)
		}

		err = setRecgCbConfig(req.IP)
		if err != nil {
			log.Println(err)
		}

	} else if dev.IP != req.IP || !dev.IsDynamic {
		dev.IP = req.IP
		err = repo.UpdateDynamicDevice(dev.DeviceId, req.IP)
		if err != nil {
			c.JSON(http.StatusInternalServerError, failedResponse)
			return
		}
	}

	//更新心跳时间
	if exist {
		repo.HeartbeatDevice(dev.DeviceId)
	}
	c.JSON(http.StatusOK, successResponse)
}

func HandleRecognizeCallback(c *gin.Context) {
	log.Println("考勤回调")
	url := serverBase + "/mbwcb/api/common/das/callback/dumux"
	bytes, err := io.ReadAll(c.Request.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, failedResponse)
		log.Println(err)
		return
	}

	resp, err := resty.New().R().SetBody(bytes).Post(url)
	if err != nil {
		c.JSON(http.StatusInternalServerError, failedResponse)
		log.Println(err)
		return
	}

	msgResp := &msgResponse{}
	err = json.Unmarshal(resp.Body(), msgResp)
	if err != nil {
		c.JSON(http.StatusInternalServerError, failedResponse)
		log.Println(err)
		return
	}
	if !msgResp.Success {
		c.JSON(http.StatusInternalServerError, failedResponse)
		log.Println(msgResp.Msg)
		return
	}
	c.JSON(http.StatusOK, successResponse)
	log.Println("回调完成")
}

func registerRecognizeCallbackToDevice(deviceIp string) error {
	url := "http://" + deviceIp + ":8080/deviceManage/setRecognitionCallback"
	resp, err := resty.New().R().SetBody(map[string]any{
		"pass":          defaultPassword,
		"callback_url":  config.GetConf().LocalIp + ":8081/callback/dumu/recognize",
		"interval_time": 10,
	}).Post(url)

	baseResp := &baseResponse{}
	err = json.Unmarshal(resp.Body(), baseResp)
	if err != nil {
		return err
	}
	if baseResp.Code != 0 {
		return errors.New(baseResp.Log)
	}
	return nil
}

// 设置人脸回调扩展选项，推送人脸照片，且只推送历史记录（否则会重复推送）
func setRecgCbConfig(deviceIp string) error {
	url := "http://" + deviceIp + ":8080/deviceManage/setRecgCbConfig"
	resp, err := resty.New().R().SetBody(map[string]any{
		"pass":            defaultPassword,
		"record_type":     2,
		"img_report_type": 0,
	}).Post(url)

	baseResp := &baseResponse{}
	err = json.Unmarshal(resp.Body(), baseResp)
	if err != nil {
		return err
	}
	if baseResp.Code != 0 {
		return errors.New(baseResp.Log)
	}
	return nil
}

func md5Str(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}
